﻿using Microsoft.Exchange.WebServices.Autodiscover;
using Microsoft.Exchange.WebServices.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;

namespace VBBLL
{
    public class emailSrv
    {

        /// <summary>
        /// test
        /// </summary>
        public void SendMeetingRequest(DateTime startTime, DateTime endTime, string location, string subject,
            string description, string[] attendees, string[] cc, string guid,
            bool iscancel, string orgUsername, string orgEmail, bool isSelf, string passWord)
        {
            try
            {
                ContentType type;
                string host = "mail.kaifa.cn";
                string address = orgEmail;//"qifanjian@kaifa.cn"; 
                //Helper.ReadConfigValue(dt, "friendlyname").ToString();
                string s = "25";
                string content = BuildIcsFormatString(startTime, endTime, location, subject,
                    description, attendees, guid, iscancel, orgUsername, orgEmail, "sys", "sys@kaifa.cn", isSelf);
                if (iscancel)
                {
                    type = new ContentType("text/calendar; method=CANCEL");
                }
                else
                {
                    type = new ContentType("text/calendar; method=REQUEST");
                }
                AlternateView item = AlternateView.CreateAlternateViewFromString(content, type);
                MailMessage message = new MailMessage();

                if (attendees != null)
                {
                    foreach (string str9 in attendees)
                    {
                        if (str9.Contains("@"))
                        {
                            string str8 = str9.Trim();
                            message.To.Add(str8);
                        }
                    }
                    message.To.Add(orgEmail);
                }
                if (cc != null)
                {
                    foreach (string str9 in cc)
                    {
                        if (str9.Contains("@"))
                        {
                            string str8 = str9.Trim();
                            message.CC.Add(str8);
                        }
                    }
                }
                message.From = new MailAddress(address);//
                message.AlternateViews.Add(item);
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.IsBodyHtml = true;

                SmtpClient client = new SmtpClient(host, int.Parse(s));
                //NetworkCredential credential = new NetworkCredential(userName, password);
                client.UseDefaultCredentials = false;
                client.Credentials = new NetworkCredential(orgUsername, passWord, "gwkf.cn");
                client.Send(message);
            }
            catch (Exception ex)
            {
                Worker.writeErrorMessage("0", ex, "SendMeetingRequest");
            }
        }



        public string BuildIcsFormatString(DateTime startTime, DateTime endTime, string location, string subject,
           string description, string[] attendees, string guid, bool iscancel, string orgUsername, string orgEmail,
           string sysOrganizer, string sysEmail, bool isSelf)
        {
            //int num = 1;
            startTime = startTime.AddHours((double)-8);
            endTime = endTime.AddHours((double)-8);
            StringBuilder builder = new StringBuilder();
            builder.AppendLine("BEGIN:VCALENDAR");
            builder.AppendLine("VERSION:2.0");
            if (iscancel)
            {
                builder.AppendLine("METHOD:CANCEL");
            }
            else
            {
                builder.AppendLine("METHOD:REQUEST");
            }
            builder.AppendLine("BEGIN:VEVENT");
            if (attendees != null)
            {
                foreach (string str in attendees)
                {
                    if (str.Contains("@"))
                    {
                        string con = str.Trim();
                        builder.AppendLine("ATTENDEE;ROLE=REQ-PARTICIPANT;RSVP=TRUE:mailto:" + con);
                    }
                }
            }

            builder.AppendLine("CLASS:PUBLIC");
            builder.AppendLine(string.Format("CREATED:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
            builder.AppendLine("DESCRIPTION:" + description);
            builder.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", endTime));
            builder.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
            builder.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", startTime));
            if (isSelf)
            {
                builder.AppendLine("ORGANIZER;CN=\"" + sysOrganizer + "\":mailto:" + sysEmail); //发件人
            }
            else
            {
                builder.AppendLine("ORGANIZER;CN=\"" + orgUsername + "\":mailto:" + orgEmail);
            }
            builder.AppendLine("SEQUENCE:0");
            builder.AppendLine("UID:" + guid);
            builder.AppendLine("LOCATION:" + location);
            builder.AppendLine("SUMMARY;LANGUAGE=en-us:" + subject);
            builder.AppendLine("BEGIN:VALARM");
            builder.AppendLine("TRIGGER:-PT15M");
            builder.AppendLine("ACTION:DISPLAY");
            builder.AppendLine("DESCRIPTION:Reminder");
            builder.AppendLine("END:VALARM");
            builder.AppendLine("END:VEVENT");
            builder.AppendLine("END:VCALENDAR");
            return builder.ToString();
        }


        private ExchangeService getService(String userEmail, String login, String password, String hostName)
        {
            ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
            AutodiscoverService auservice = new AutodiscoverService(hostName);
            if (auservice.ServerInfo != null)
            {
                try
                {
                    service.AutodiscoverUrl(userEmail);
                }
                catch (AutodiscoverRemoteException ex)
                {
                    Console.WriteLine("Exception thrown: " + ex.Error.Message);
                }
            }
            else
            {
                service.Url = new Uri("https://" + hostName + "/EWS/Exchange.asmx");
            }
            service.UseDefaultCredentials = true;
            if (service.ServerInfo == null)
            {
                service.Credentials = new WebCredentials(login, password);
            }
            return service;
        }

        /// <summary>
        /// 发送周期性会议通知
        /// </summary>
        /// <param name="bookingID"></param>
        /// <param name="userName"></param>
        /// <param name="participants"></param>
        /// <param name="cc"></param>
        /// <param name="meetingTheme"></param>
        /// <param name="meetingAbstract"></param>
        /// <param name="mtrAdd"></param>
        /// <param name="mtrNo"></param>
        /// <param name="specialRequestFirst"></param>
        /// <param name="specialRequestSecond"></param>
        /// <param name="st"></param>
        /// <param name="et"></param>
        /// <param name="startDate"></param>
        /// <param name="startTime"></param>
        /// <param name="endDate"></param>
        /// <param name="endTime"></param>
        /// <param name="weeks"></param>
        /// <param name="passWord"></param>
        /// <returns></returns>
        public string sendPeriodicMeetingMessage(string bookingID, string userName, string participants, string cc, string meetingTheme,
          string meetingAbstract, string mtrAdd, int mtrNo, string specialRequestFirst, string specialRequestSecond,
          DateTime st, DateTime et, string startDate, string startTime, string endDate, string endTime, string[] weeks, string passWord)
        {
            string[] participant = participants.Split(';');
            string[] ccs = cc.Split(';');
            try
            {
                // 实例化ExchageService
                ExchangeService service1 = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
                // 指定用户名，密码，和域名
                service1.Credentials = new WebCredentials(userName, passWord, "gwkf.cn");
                // 指定Exchage服务的url地址
                service1.Url = new Uri(@"https://mail.kaifa.cn/ews/exchange.asmx");
                // 指定邮箱账号
                service1.AutodiscoverUrl(userName + "@kaifa.cn");
                // service.Credentials = new WebCredentials("jundu", "470061490", "kaifa.cn");
                // service.Url = new Uri(@"https://mail.kaifa.cn/ews/exchange.asmx");
                Appointment appointment = new Appointment(service1);
                appointment.Subject = meetingTheme;
                appointment.Body = string.Format(meetingAbstract);
                appointment.Start = st;
                appointment.End = new DateTime(st.Year, st.Month, st.Day, et.Hour, et.Minute, et.Second);// appointment.Start.AddHours(1);
                appointment.Location = mtrAdd;//

                foreach (string par in participant)
                {
                    if (par.Contains("@"))
                    {
                        string str = par.Trim();
                        appointment.RequiredAttendees.Add(str);
                    }
                }
                //appointment
                Microsoft.Exchange.WebServices.Data.DayOfTheWeek[] days = new Microsoft.Exchange.WebServices.Data.DayOfTheWeek[weeks.Length];
                int s = 0;
                foreach (string weekday in weeks)
                {
                    if (weekday == "Monday") days[s] = DayOfTheWeek.Monday;
                    else if (weekday == "Tuesday") days[s] = DayOfTheWeek.Tuesday;
                    else if (weekday == "Wednesday") days[s] = DayOfTheWeek.Wednesday;
                    else if (weekday == "Thursday") days[s] = DayOfTheWeek.Thursday;
                    else if (weekday == "Friday") days[s] = DayOfTheWeek.Friday;
                    else if (weekday == "Saturday") days[s] = DayOfTheWeek.Saturday;
                    else if (weekday == "Sunday") days[s] = DayOfTheWeek.Sunday;
                    s = s + 1;
                }

                appointment.Recurrence = new Recurrence.WeeklyPattern(
                    appointment.Start.Date,
                    1,
                    days
                     );
                appointment.Recurrence.StartDate = appointment.Start.Date;
                appointment.Recurrence.EndDate = new DateTime(et.Year, et.Month, et.Day);
                // Save the recurring series.
                appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);
                #region
                /*
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
                service.TraceEnabled = true;
                service.Credentials = new NetworkCredential(userName, "hsw852123", "kaifa.cn");
                service.Url = new Uri(@"https://mail.kaifa.cn/ews/exchange.asmx");
                service.UseDefaultCredentials = true;

                service.AutodiscoverUrl(userName+"@kaifa.cn");//程序可以自动获取到与服务器通信的设置方式
                Appointment appointment = new Appointment(service);
                appointment.Subject = meetingTheme;//
                appointment.Body = meetingAbstract;
                appointment.Start = st;
                appointment.End = et;
                appointment.ICalUid = bookingID;
                appointment.Location = mtrAdd;

                foreach (string par in participant)
                {
                    if (par.Contains("@"))
                    {
                        appointment.RequiredAttendees.Add(par);
                    }
                }
                Microsoft.Exchange.WebServices.Data.DayOfTheWeek[] weekdays = new Microsoft.Exchange.WebServices.Data.DayOfTheWeek[weeks.Length];
                int s = 0;
                foreach (string weekday in weeks)
                {
                    if (weekday == "Monday") weekdays[s] =DayOfTheWeek.Monday;
                    else if (weekday == "Tuesday") weekdays[s] = DayOfTheWeek.Tuesday;
                    else if (weekday == "Wednesday") weekdays[s] = DayOfTheWeek.Wednesday;
                    else if (weekday == "Thursday") weekdays[s] = DayOfTheWeek.Thursday;
                    else if (weekday == "Friday") weekdays[s] = DayOfTheWeek.Friday;
                    else if (weekday == "Saturday") weekdays[s] = DayOfTheWeek.Saturday;
                    else if (weekday == "Sunday") weekdays[s] = DayOfTheWeek.Sunday;
                    s = s + 1;
                }
                DayOfTheWeek[] days2 = new DayOfTheWeek[] 
                { 
                    DayOfTheWeek.Monday,
                    DayOfTheWeek.Wednesday 
                };
                appointment.Recurrence = new Recurrence.WeeklyPattern(
                    appointment.Start.Date,
                    1,
                    weekdays
                    );
                appointment.Recurrence.StartDate = appointment.Start.Date;
                appointment.Recurrence.EndDate = new DateTime(et.Year, et.Month, et.Day);
               
                appointment.Save(SendInvitationsMode.SendToAllAndSaveCopy);
                string aa = appointment.Id.UniqueId;
                */
                #endregion
            }
            catch (Exception e)
            {
                return e.Message;
            }
            return null;
        }



    }
}
